package com.okilo.online.app.lib.analyse.util

import android.app.Application
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.google.android.gms.tasks.Task
import com.google.firebase.analytics.FirebaseAnalytics
import com.okilo.online.app.BuildConfig
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.configs.OkiloConfigs.addParams
import com.okilo.online.app.lib.analyse.OkiloAnalyseUtil
import com.okilo.online.app.pet.OkiloLibPet
import com.okilo.online.app.tools.log.OkiloLog
import org.json.JSONObject
import java.util.Locale


/**
 * Firebase
 */
object OkiloFireUtil {

    /** firebase app id, 服务端回推firebase事件使用 */
    private var firebaseAppId: String = ""

    /** ga4 instance id, 服务端回推firebase事件使用 */
    private var ga4InstanceId: String = ""

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application,success: (String,String) -> Unit) {
        try {
            if (firebaseAppId.isBlank()) {
                Thread {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        firebaseAppId = FirebaseAnalytics.getInstance(context).firebaseInstanceId
                        OkiloLog.i("mFirebaseAppId=$firebaseAppId")

                        if (firebaseAppId.isNotBlank()){
                            Handler(Looper.getMainLooper()).post {
                                //回调通知
                                success.invoke(getFirebaseAppId(), getGa4InstanceId())
                            }
                        }
                    } else {
                        OkiloLog.i("init Firebase ERROR! Cannot call in the main thread, You must call in the other thread")
                    }
                }.start()
            } else {
                Handler(Looper.getMainLooper()).post {
                    //回调通知
                    success.invoke(getFirebaseAppId(), getGa4InstanceId())
                }
            }

            if (ga4InstanceId.isBlank()) {
                val gResult: Task<String?> = FirebaseAnalytics.getInstance(context).appInstanceId
                gResult.addOnSuccessListener {
                    ga4InstanceId = it?:""
                    OkiloLog.i("mGa4InstanceId=$ga4InstanceId")

                    if (ga4InstanceId.isNotBlank()){
                        Handler(Looper.getMainLooper()).post {
                            //回调通知
                            success.invoke(getFirebaseAppId(), getGa4InstanceId())
                        }
                    }
                }
            } else {
                //回调通知
                success.invoke(getFirebaseAppId(), getGa4InstanceId())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存 firebase 信息
     */
    fun submitFirebaseInfo() {
        if (OkiloConfigs.gOkiloLoginToken().isEmpty()) return
        val params = JSONObject().addParams().apply {
            put("path", OkiloConfigs.gOkiloRequestPath("FIREBASE"))
            put("name", BuildConfig.packageName)
            put("OSAndVersion", "Android ${Build.VERSION.RELEASE}")
            put("locale", Locale.getDefault().toString())
            put("device", Build.MODEL.toString())
            put("appVersion", BuildConfig.VERSION_CODE.toString())
            put("sdkVersion", Build.VERSION.SDK_INT.toString())
            put("device", "Build/${Build.ID}")
            put("lat", OkiloAnalyseUtil.getAdEnabled().toString())
            put("firebaseAppId", getFirebaseAppId())
            put("ga4AppInstanceId", getGa4InstanceId())
        }
        OkiloLibPet.submitOkiloLibDataRequest(params)
    }

    /**
     * 获取Firebase App Id
     */
    private fun getFirebaseAppId(): String {
        return firebaseAppId
    }

    /**
     * 获取Firebase Ga4 instance Id
     */
    private fun getGa4InstanceId(): String {
        return ga4InstanceId
    }
}